import os from 'os';
import fs from 'fs/promises';
import path from 'path';

/**
 * 获取系统信息
 */
export async function getSystemInfo() {
  const cpus = os.cpus();
  const totalMemory = os.totalmem();
  const freeMemory = os.freemem();
  const usedMemory = totalMemory - freeMemory;
  
  return {
    platform: os.platform(),
    arch: os.arch(),
    nodeVersion: process.version,
    hostname: os.hostname(),
    uptime: os.uptime(),
    loadAverage: os.loadavg(),
    cpuCount: cpus.length,
    cpuModel: cpus[0]?.model || 'Unknown',
    cpuSpeed: cpus[0]?.speed || 0,
    memory: {
      total: totalMemory,
      free: freeMemory,
      used: usedMemory,
      usagePercent: Math.round((usedMemory / totalMemory) * 100)
    },
    disk: await getDiskUsage()
  };
}

/**
 * 获取磁盘使用情况
 */
async function getDiskUsage() {
  try {
    const stats = await fs.stat(process.cwd());
    // 简单的磁盘使用情况，实际应用中可能需要更复杂的实现
    return {
      available: 'N/A',
      used: 'N/A',
      total: 'N/A'
    };
  } catch (error) {
    return {
      available: 'N/A',
      used: 'N/A',
      total: 'N/A',
      error: error instanceof Error ? error.message : 'Unknown error'
    };
  }
}

/**
 * 获取进程信息
 */
export function getProcessInfo() {
  const memoryUsage = process.memoryUsage();
  const cpuUsage = process.cpuUsage();
  
  return {
    pid: process.pid,
    ppid: process.ppid,
    uptime: process.uptime(),
    memoryUsage: {
      rss: memoryUsage.rss,
      heapTotal: memoryUsage.heapTotal,
      heapUsed: memoryUsage.heapUsed,
      external: memoryUsage.external,
      arrayBuffers: memoryUsage.arrayBuffers
    },
    cpuUsage: {
      user: cpuUsage.user,
      system: cpuUsage.system
    }
  };
}

/**
 * 获取应用信息
 */
export function getAppInfo() {
  return {
    name: process.env.npm_package_name || 'Dimensional Echo Backend',
    version: process.env.npm_package_version || '1.0.0',
    environment: process.env.NODE_ENV || 'development',
    startTime: new Date(Date.now() - process.uptime() * 1000).toISOString()
  };
}